package com.msb.mall.ware.service.impl;

import com.msb.common.constant.WareConstant;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.WareSkuService;
import com.msb.mall.ware.vo.MergeVO;
import com.msb.mall.ware.vo.PurchaseDetailDoneVO;
import com.msb.mall.ware.vo.PurchaseDoneVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
              new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     *  查询采购单为 新建 或者为 已分配 的采购单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils listUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 完成采购需求单的合并操作和更新status状态
     * @param mergeVO
     */
    @Transactional
    @Override
    public void merge(MergeVO mergeVO) {

        //根据id判断是否有这个采购单，没有就新建
        Long purchaseId =mergeVO.getPurchaseId();
        if (purchaseId == null) {
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            //相当于给上面的purchaseId重新赋值
            purchaseId = purchaseEntity.getId();
        }
        //要么是赋值的采购单id，要么不是
        Long findpurchaseId=purchaseId;
        Long[] items = mergeVO.getItems();
        // 更新采购需求单
        List<Long> longs = Arrays.asList(items);
        List<PurchaseDetailEntity> list = longs.stream().map((m) -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            // 更新每一条 需求单的 采购单编号
            purchaseDetailEntity.setId(m);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            purchaseDetailEntity.setPurchaseId(findpurchaseId);

            return purchaseDetailEntity;

        }).collect(Collectors.toList());
        //根据采购需求单id更新
        purchaseDetailService.updateBatchById(list);

        // 更新对应的采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(findpurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        //根据采购单id更新
        this.updateById(purchaseEntity);
    }

    /**
     * 领取采购单
     * @param ids
     */
    @Transactional
    @Override
    public void receive(List<Long> ids) {

        // 1.领取的采购单的状态只能是新建或者已分配的采购单 其他的是不能领取的
        List<PurchaseEntity> list = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            //过滤不是新建，已分配的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                //是新建，已分配的采购单就放行
                return true;
            }
            //不是新建，已分配的采购单就过滤
            return false;
        }).map(item -> {
            // 更新采购单的状态为 已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            // 设置更新时间
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        // 更新采购单的状态为 已领取
        this.updateBatchById(list);


        for (Long id : ids) {
            // 根据采购单id 找到对应的采购需求单对象
            List<PurchaseDetailEntity> purchaseDetailEntities
                    = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
            List<PurchaseDetailEntity> collect1 = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {

                PurchaseDetailEntity purchaseDetailEntity1 = new PurchaseDetailEntity();
                purchaseDetailEntity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                purchaseDetailEntity1.setId(purchaseDetailEntity.getId());

                return purchaseDetailEntity1;
            }).collect(Collectors.toList());
            // 批量更新采购项
            purchaseDetailService.updateBatchById(collect1);
        }
    }

    /**
     * 1.只要采购需求单中有一个有问题，那么采购单就是有异常的
     * 2.只有采购需求单中没有问题，都是已完成，采购单就是已完成，
     * 所以下面就先判断采购需求单状态，然后再判断采购单的状态
     * @param vo
     */
    @Transactional
    @Override
    public void Done(PurchaseDoneVO vo) {
        // 获取所有的采购需求单
        List<PurchaseDetailDoneVO> items = vo.getItems();

        List<PurchaseDetailEntity> list = new ArrayList<>();
        // 改变采购需求单的状态
        boolean flag=true; // 记录采购的状态 默认为 完成
        for (PurchaseDetailDoneVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //判断采购需求单的状态是否有异常
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                purchaseDetailEntity.setStatus(item.getStatus());
                // 该采购项采购出现了问题
                flag = false;
            } else {
                // 采购项采购成功
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                // 3.将采购成功的采购项进入库操作
                // 跟具采购需求单编号查询出对应的采购需求单详情信息
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getSkuNum(), detailEntity.getWareId());


            }
            purchaseDetailEntity.setId(item.getItemId());
            list.add(purchaseDetailEntity);
        }

        // 批量更新 采购需求单
        purchaseDetailService.updateBatchById(list);

        // 1.根据采购单id改变采购单的状态
        PurchaseEntity purchaseEntity = this.getById(vo.getId());
        //判断flag是true还是false，要是false说明采购需求单有异常所以我们的采购单也有异常，true就没有异常
        purchaseEntity.setStatus(flag==true
                ?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                :WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }
}